package com.graden.background.service.sysrolemenu.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graden.background.service.sysmenu.ISysMenuService;
import com.graden.background.repository.sysmenu.entity.SysMenuNode;
import com.graden.background.repository.sysrolemenu.SysRoleMenuMapper;
import com.graden.background.repository.sysrolemenu.entity.SysRoleMenu;
import com.graden.background.service.sysrolemenu.ISysRoleMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 角色菜单服务实现类
 * </p>
 *
 * @author
 * @since 2019-03-26
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

	@Resource
	ISysMenuService iSysMenuService;

	@Resource
	ISysRoleMenuService iSysRoleMenuService;


	@Override
	public List<SysMenuNode> getRoleMenuTree(boolean isAdmin) {
		//菜单模板
		List<SysMenuNode> sysMenuNodes = iSysMenuService.getMenuNodeTree();

		QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
		List<SysRoleMenu> sysRoleMenus = iSysRoleMenuService.list(queryWrapper);

		for (SysRoleMenu item : sysRoleMenus) {
			setPowerToRecursion(item.getMenuId(), sysMenuNodes);
		}

		if (!isAdmin) {
			removeNoPowerMenu(sysMenuNodes);
		}

		return sysMenuNodes;
	}

	private void setPowerToRecursion(int menuId, List<SysMenuNode> nextMenuNode) {

		for (SysMenuNode item : nextMenuNode) {
			if (item.getId() == menuId) {
				item.setPower(true);
				break;
			}
			setPowerToRecursion(menuId, item.getNext());
		}
	}

	private void removeNoPowerMenu(List<SysMenuNode> baseMenuNodes) {
		for (int i = 0; i < 3; i++) {
			removeNoPowerMenuToRecursion(baseMenuNodes);
		}
	}


	private void removeNoPowerMenuToRecursion(List<SysMenuNode> nextMenuNodes) {
		Iterator<SysMenuNode> it = nextMenuNodes.iterator();
		while (it.hasNext()) {
			SysMenuNode item = it.next();
			if (!item.isPower() && item.getNext().isEmpty()) {
				it.remove();
			} else if (!item.getNext().isEmpty()) {
				removeNoPowerMenuToRecursion(item.getNext());
			}
		}
	}


	/**
	 * 插入角色和菜单权限关联表
	 */
	@Override
	public void saveMenu(Integer roleId, Integer[] menuIds) {
		SysRoleMenu sysRoleMenu = new SysRoleMenu();
		sysRoleMenu.setId(0);
		sysRoleMenu.setRoleId(roleId);
		sysRoleMenu.setUpdateTime(LocalDateTime.now());
		sysRoleMenu.setCreateTime(LocalDateTime.now());

		for (Integer menuId : menuIds) {
			if (!Objects.isNull(menuId)) {
				if (iSysMenuService.getById(menuId) != null) {
					sysRoleMenu.setMenuId(menuId);
					this.save(sysRoleMenu);
				}
			}
		}
	}


}
